package com.ltcode.lock.starter.config;

import com.ltcode.lock.starter.handle.LockHandle;
import com.ltcode.lock.starter.inface.DistributedLock;
import com.ltcode.lock.starter.management.DistributedLockManagement;
import com.ltcode.lock.starter.utils.LockUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

@Configuration
@EnableConfigurationProperties({RedissonProperties.class})
public class RedissonLockConfig {

    private final RedissonProperties redissonProperties;

    public RedissonLockConfig(RedissonProperties redissonProperties) {
        this.redissonProperties = redissonProperties;
    }

    /**
     * 初始化redisson 客户端
     * @return
     */
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress(redissonProperties.getAddress())
                .setTimeout(redissonProperties.getTimeout())
                .setConnectionPoolSize(redissonProperties.getConnectionPoolSize())
                .setDatabase(redissonProperties.getDatabase())
                .setConnectionMinimumIdleSize(redissonProperties.getConnectionMinimumIdleSize());
        if(!ObjectUtils.isEmpty(redissonProperties.getPassword())){
            serverConfig.setPassword(redissonProperties.getPassword());
        }
        return Redisson.create(config);

    }

    /**
     * 绑定实现类与redisson 客户端
     *
     * @param redissonClient
     * @return
     */
    @Bean
    public DistributedLock distributedLock(RedissonClient redissonClient) {
        DistributedLockManagement distributedLockManagement = new DistributedLockManagement();
        distributedLockManagement.setRedissonClient(redissonClient);
        LockUtil.setDistributedLock(distributedLockManagement);
        return distributedLockManagement;
    }
    @Bean
    public LockHandle lockHandle() {
        return new LockHandle();
    }
}
